package com.example.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Bitmap 帮助类之一
 */
public class BitmapUtils {

    /**
     * Save Bitmap
     *
     * @param bitmapname file name
     * @param bm  picture to save
     */
    public static String saveBitmap(String bitmapname, Bitmap bm, Context mContext) {
        //指定我们想要存储文件的地址
        String TargetPath = mContext.getFilesDir() + "/images/";
        //判断指定文件夹的路径是否存在
        if (!FileUtils.fileIsExist(TargetPath)) {
            return null;
        } else {
            //如果指定文件夹创建成功，那么我们则需要进行图片存储操作
            File saveFile = new File(TargetPath, bitmapname);

            try {
                FileOutputStream saveImgOut = new FileOutputStream(saveFile);
                // compress - 压缩的意思
                bm.compress(Bitmap.CompressFormat.JPEG, 80, saveImgOut);
                //存储完成后需要清除相关的进程
                saveImgOut.flush();
                saveImgOut.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return saveFile.getPath();
        }
    }
    public static Bitmap loadBitmap(String imagepath){
        if (imagepath==null||imagepath.equals(""))return null;
        File file=new File(imagepath);
        if (!file.exists()) {
            Log.d("输出","空路径");
            return null;
        }
        else{
            Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
            return bitmap;
        }
    }

    public static Bitmap uriToBitmap(Uri uri,Context context) {
        Bitmap bitmap;
        try {
            bitmap= BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return bitmap;
    }

}
